package com.dinstar.linphone.core;

import static java.lang.System.in;

import android.content.Context;
import android.util.Log;


import com.dinstar.linphone.R;

import org.linphone.core.Config;
import org.linphone.core.Factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CorePreferences {

    private Context mContext;
    public Config config;
    public String basePath;
    public String configPath;
    public String factoryConfigPath;
    public String linphoneDefaultValuesPath;
    public String defaultValuesPath;
    public String userCertificatesPath;

    public CorePreferences(Context context) {
        mContext = context;
        basePath = mContext.getFilesDir().getAbsolutePath();
        configPath = basePath + "/.linphonerc";
        factoryConfigPath = basePath + "/linphonerc";
        linphoneDefaultValuesPath = basePath + "/assistant_linphone_default_values";
        defaultValuesPath = basePath + "/assistant_default_values";
        userCertificatesPath = basePath + "/user-certs";

        config = Factory.instance().createConfigWithFactory(
                configPath,
                factoryConfigPath
        );
        String TagName = mContext.getString(R.string.app_name);
        Factory.instance().setDebugMode(isDebugEnabled(), TagName);

    }

    public Config getConfig(){
        return (config != null)? config:null;
    }

    /***
     * 是否开启debug
     * @return
     */
    public boolean isDebugEnabled() {
        if (config == null) return false;
        return config.getBool("app", "debug", false);
    }

    public CorePreferences enabledDebug(boolean enabled) {
        if (config == null) return null;
        config.setBool("app", "debug", enabled);
        return this;
    }

    /***
     * 是否开启自动应答
     * @return
     */
    public boolean isAutoAnswerEnabled() {
        if (config == null) return false;
        return config.getBool("app", "auto_answer", false);
    }

    public CorePreferences enableAutoAnswer(boolean enable) {
        if (config == null) return null;
        config.setBool("app", "auto_answer", enable);
        return this;
    }

    /***
     * 自动应答时间
     * @return
     */
    public int getAutoAnswerTime() {
        if (config == null) return 0;
        return config.getInt("app", "auto_answer_delay", 0);
    }

    public CorePreferences setAutoAnswerTime(int time) {
        if (config == null) return null;
        config.setInt("app", "auto_answer_delay", time);
        return this;
    }

    /***
     * 获取语音箱地址
     * @return
     */
    public String getVoiceMailUri() {
        if (config == null) return null;
        return config.getString("app", "voice_mail", null);
    }

    public CorePreferences setVoiceMailUri(String uri) {
        if (config == null) return null;
        config.setString("app", "voice_mail", uri);
        return this;
    }

    /***
     * 是否开启：被拒绝通话转到语音箱
     * @return
     */
    public boolean isRedirectDeclinedCallToVoiceMail() {
        if (config == null) return false;
        return config.getBool("app", "redirect_declined_call_to_voice_mail", true);
    }

    public CorePreferences enabledRedirectDeclinedCallToVoiceMail(boolean value) {
        if (config == null) return null;
        config.setBool("app", "redirect_declined_call_to_voice_mail", value);
        return this;
    }

    /**
     * 是否获取可用蓝牙设备
     * @return
     */
    public boolean isRouteAudioToBluetoothIfAvailable() {
        if (config == null) return false;
        return config.getBool("app", "route_audio_to_bluetooth_if_available", true);
    }

    public CorePreferences enabledRouteAudioToBluetoothIfAvailable(boolean value) {
        if (config == null) return null;
        config.setBool("app", "route_audio_to_bluetooth_if_available", value);
        return this;
    }

    /***
     * 视频通话是否启用扬声器
     * @return
     */
    public boolean isRouteAudioToSpeakerWhenVideoIsEnabled() {
        if (config == null) return false;
        return config.getBool("app", "route_audio_to_speaker_when_video_enabled", true);
    }

    public CorePreferences enabledRouteAudioToSpeakerWhenVideoIsEnabled(boolean value) {
        if (config == null) return null;
        config.setBool("app", "route_audio_to_speaker_when_video_enabled", value);
        return this;
    }

    /***
     * 获取xmlrpc_url
     * @return
     */
    public String getXmlrpcUrl() {
        if (config == null) return null;
        return config.getString("assistant", "xmlrpc_url", null);
    }

    public void setXmlrpcUrl(String value) {
        if (config == null) return;
        config.setString("assistant", "xmlrpc_url", value);
    }

    public void copyAssetsFromPackage() {
        copy("linphonerc_default", configPath, false);
        copy("linphonerc_factory", factoryConfigPath, true);
        copy("assistant_linphone_default_values", linphoneDefaultValuesPath, true);
        copy("assistant_default_values", defaultValuesPath, true);

        move(basePath + "/linphone-log-history.db", basePath + "/call-history.db", false);
        move(basePath + "/zrtp_secrets", basePath + "/zrtp-secrets.db", false);
    }

    private void copy(String from, String to, boolean overrideIfExists) {
        File outFile = new File(to);
        if (outFile.exists()) {
            if (!overrideIfExists) {
                Log.i(mContext.getString(R.string.app_name), "[CorePreferences] copy文件" + from + "已经存在，路径：" + to);
                return;
            }
        }
        Log.i(mContext.getString(R.string.app_name), "[CorePreferences] 从assets copy" + from + "文件，路径：" + to);
        try {
            OutputStream outStream = new FileOutputStream(outFile);
            InputStream inFile = mContext.getAssets().open(from);
            byte[] buffer = new byte[1024];
            int length = inFile.read(buffer);

            while (length > 0) {
                outStream.write(buffer, 0, length);
                length = inFile.read(buffer);
            }
            inFile.close();
            outStream.flush();
            outStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void move(String from, String to, boolean overrideIfExists) {
        File inFile = new File(from);
        File outFile = new File(to);
        if (inFile.exists()) {
            if (outFile.exists() && !overrideIfExists) {
                Log.w(mContext.getString(R.string.app_name), "[CorePreferences] move文件" + from + "已经存在，路径：" + to);
            } else {
                try {
                    InputStream inStream = new FileInputStream(inFile);
                    OutputStream outStream = new FileOutputStream(outFile);

                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = in.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }

                    inStream.close();
                    outStream.flush();
                    outStream.close();

                    inFile.delete();
                    Log.i(mContext.getString(R.string.app_name), "[CorePreferences] move文件" + from + "完成，路径：" + to);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        } else {
            Log.w(mContext.getString(R.string.app_name), "[CorePreferences] move" + from + "文件失败，没有文件资源");
        }
    }

}
